package com.zhijian.medical.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.zhijian.medical.dao.local.DigitalSliceCaseMapper;
import com.zhijian.medical.entity.po.DigitalSliceCase;
import com.zhijian.medical.entity.vo.request.*;
import com.zhijian.medical.entity.vo.response.DigitalSliceCaseVo;
import com.zhijian.medical.enums.DigitalSliceCaseCollectLikeEnum;
import com.zhijian.medical.enums.FileTypeEnum;
import com.zhijian.medical.holder.CurrentUserHolder;
import com.zhijian.medical.service.DigitalSliceCaseCollectLikeService;
import com.zhijian.medical.service.DigitalSliceCaseDifferentialDiagnosisService;
import com.zhijian.medical.service.DigitalSliceCaseService;
import com.zhijian.medical.service.FileService;
import com.zhijian.medical.util.AssertUtil;
import com.zhijian.medical.util.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 数字切片-病例业务处理层
 *
 * @author HCG
 * @version: 1.0
 * @date 2022-12-30 15:12:49
 */
@Slf4j
@Service
public class DigitalSliceCaseServiceImpl implements DigitalSliceCaseService {

    @Autowired
    private DigitalSliceCaseMapper mapper;

    @Autowired
    private DigitalSliceCaseCollectLikeService digitalSliceCaseCollectLikeService;

    @Autowired
    private DigitalSliceCaseDifferentialDiagnosisService digitalSliceCaseDifferentialDiagnosisService;

    @Autowired
    private FileService fileService;

    @Override
    public DigitalSliceCase selectById(Long id) {
        return mapper.selectByPrimaryKey(id);
    }

    @Override
    public DigitalSliceCase selectByCaseId(String caseId) {
        return mapper.selectByCaseId(caseId);
    }

    @Override
    public DigitalSliceCaseVo selectVoById(Long id) {
        DigitalSliceCaseVo digitalSliceCaseVo = mapper.selectVoById(id);
        if (Objects.isNull(digitalSliceCaseVo)) {
            return null;
        }
        //鉴别诊断
        digitalSliceCaseVo.setDifferentialDiagnosisList(digitalSliceCaseDifferentialDiagnosisService.selectList(DigitalSliceCaseDifferentialDiagnosisSearchVo.builder()
                .caseId(digitalSliceCaseVo.getId())
                .build()));
        return digitalSliceCaseVo;
    }

    @Override
    public void deleteById(Long id) {
        mapper.deleteByPrimaryKey(id);
    }

    @Override
    public Long insert(DigitalSliceCase digitalSliceCase) {
        Date now = new Date();
        digitalSliceCase.setCreateTime(now);
        digitalSliceCase.setUpdateTime(now);
        digitalSliceCase.setUploadTime(now);
        digitalSliceCase.setUploadUserId(CurrentUserHolder.getUser().getId());
        digitalSliceCase.setAuthor(CurrentUserHolder.getUser().getName());
        return mapper.insert(digitalSliceCase) > 0 ? digitalSliceCase.getId() : 0L;
    }

    @Override
    public boolean update(DigitalSliceCase digitalSliceCase) {
        Date now = new Date();
        digitalSliceCase.setUpdateTime(now);
        return mapper.updateByPrimaryKey(digitalSliceCase) != 0;
    }

    @Override
    public boolean updateByPrimaryKeySelective(DigitalSliceCase record) {
        Date now = new Date();
        record.setUpdateTime(now);
        return mapper.updateByPrimaryKeySelective(record) != 0;
    }

    @Override
    public Integer count(DigitalSliceCaseSearchVo digitalSliceCaseSearchVo) {
        return mapper.count(digitalSliceCaseSearchVo);
    }

    @Override
    public List<DigitalSliceCaseVo> selectList(DigitalSliceCaseSearchVo digitalSliceCaseSearchVo) {
        List<DigitalSliceCaseVo> digitalSliceCaseVos = mapper.selectList(digitalSliceCaseSearchVo);
        if (CollectionUtil.isEmpty(digitalSliceCaseVos)) {
            return Collections.emptyList();
        }
        if (Objects.nonNull(digitalSliceCaseSearchVo.getLoginUserId())) {
            //如果有当前登录人id做为条件，就把是否收藏也拉出来
            digitalSliceCaseVos.forEach(digitalSliceCaseVo -> {
                //是否收藏
                Integer count = digitalSliceCaseCollectLikeService.count(DigitalSliceCaseCollectLikeSearchVo.builder()
                        .caseId(digitalSliceCaseVo.getId())
                        .userId(digitalSliceCaseSearchVo.getLoginUserId())
                        .type(DigitalSliceCaseCollectLikeEnum.COLLECT.getCode().byteValue())
                        .build());
                digitalSliceCaseVo.setWeatherCollect(count > 0);
            });
        }
        //把鉴别诊断查出来，赋值
        digitalSliceCaseVos.forEach(digitalSliceCaseVo -> {
            //是否点赞
            Integer count = digitalSliceCaseCollectLikeService.count(DigitalSliceCaseCollectLikeSearchVo.builder()
                    .caseId(digitalSliceCaseVo.getId())
                    .userId(digitalSliceCaseSearchVo.getLoginUserId())
                    .type(DigitalSliceCaseCollectLikeEnum.LIKE.getCode().byteValue())
                    .build());
            digitalSliceCaseVo.setWeatherLike(count > 0);
            digitalSliceCaseVo.setDifferentialDiagnosisList(digitalSliceCaseDifferentialDiagnosisService.selectList(DigitalSliceCaseDifferentialDiagnosisSearchVo.builder()
                    .caseId(digitalSliceCaseVo.getId())
                    .build()));
            //当前登录人是否是作者
            digitalSliceCaseVo.setWeatherIsAuthor(Objects.equals(digitalSliceCaseVo.getUploadUserId(), CurrentUserHolder.getUser().getId()));
            //讲解音频文件
            digitalSliceCaseVo.setAudioFilePathList(fileService.selectList(FileSearchVo.builder()
                    .dataId(digitalSliceCaseVo.getId())
                    .type(FileTypeEnum.QP_AUDIO.getCode().byteValue())
                    .build()));
            //讲解视频文件
            digitalSliceCaseVo.setVideoFilePathList(fileService.selectList(FileSearchVo.builder()
                    .dataId(digitalSliceCaseVo.getId())
                    .type(FileTypeEnum.QP_VIDEO.getCode().byteValue())
                    .build()));
        });
        return digitalSliceCaseVos;
    }

    @Override
    public List<DigitalSliceCaseVo> selectOnlyList(DigitalSliceCaseSearchVo digitalSliceCaseSearchVo) {
        return mapper.selectList(digitalSliceCaseSearchVo);
    }

    @Override
    public List<DigitalSliceCaseVo> selectListOnly(DigitalSliceCaseSearchVo digitalSliceCaseSearchVo) {
        return mapper.selectList(digitalSliceCaseSearchVo);
    }

    @Override
    public Page<DigitalSliceCaseVo> selectPage(DigitalSliceCaseSearchVo digitalSliceCaseSearchVo) {
        //先直接查总数
        int count = count(digitalSliceCaseSearchVo);
        //分页
        Page<DigitalSliceCaseVo> page = new Page<>(true, count, digitalSliceCaseSearchVo.getPageNum(), digitalSliceCaseSearchVo.getPageSize());
        digitalSliceCaseSearchVo.setStartIndex(page.getStartIndex());
        page.setPage(true);
        page.setTotalCount(count);
        List<DigitalSliceCaseVo> responseVos = this.selectList(digitalSliceCaseSearchVo);
        page.setData(responseVos);
        return page;
    }

    @Override
    public boolean insertBatch(List<DigitalSliceCase> entities) {
        return CollectionUtil.isNotEmpty(entities) && mapper.insertBatch(entities) > 0;
    }

    @Transactional(rollbackFor = Exception.class, value = "localTransactionManager")
    @Override
    public boolean updateBottomInfo(DigitalSliceCaseUpdateBottomVo param) {
        DigitalSliceCase digitalSliceCase = this.selectById(param.getId());
        AssertUtil.notNull(digitalSliceCase, "此病例不存在或者已被删除");
        AssertUtil.check(!Objects.equals(digitalSliceCase.getUploadUserId(), CurrentUserHolder.getUser().getId()), "您没有权限进行操作");
        //讲解音频文件
        fileService.insertBatch(param.getAudioFilePathList(), FileTypeEnum.QP_AUDIO.getCode().byteValue(), param.getId());
        //讲解视频文件
        fileService.insertBatch(param.getAudioFilePathList(), FileTypeEnum.QP_VIDEO.getCode().byteValue(), param.getId());
        return this.updateByPrimaryKeySelective(DigitalSliceCase.builder()
                .id(param.getId())
                .clinicalData(param.getClinicalData())
                .generalFindings(param.getGeneralFindings())
                .pathologicDiagnosis(param.getPathologicDiagnosis())
                .causeAnalysis(param.getCauseAnalysis())
                .fzbl(param.getFzbl())
                .writingNote(param.getWritingNote())
                .build());
    }

    @Override
    public boolean updateTopInfo(DigitalSliceCaseUpdateTopVo param) {
        DigitalSliceCase digitalSliceCase = this.selectById(param.getId());
        AssertUtil.notNull(digitalSliceCase, "此病例不存在或者已被删除");
        AssertUtil.check(!Objects.equals(digitalSliceCase.getUploadUserId(), CurrentUserHolder.getUser().getId()), "您没有权限进行操作");
        return this.updateByPrimaryKeySelective(DigitalSliceCase.builder()
                .id(param.getId())
                .caseId(param.getCaseId())
                .uploadFactory(param.getUploadFactory())
                .sourcePathologyNo(param.getSourcePathologyNo())
                .samplingPosition(param.getSamplingPosition())
                .build());
    }

    @Override
    public String createNextCaseId() {
        //今年
        String year = DateUtil.format(new Date(), new SimpleDateFormat("yyyy"));
        //今年最大的分子病理号
        String caseId = this.selectMaxCaseIdByYear(year);
        if (StringUtils.isBlank(caseId)) {
            //如果为空，说明这是今年第一个
            return String.format("WB%s%s", year, "00001");
        }
        //替换掉M后，剩下的加1即可
        String m = caseId.replace("WB", "");
        Integer mI = Integer.valueOf(m);
        return String.format("WB%s", mI + 1);
    }

    @Override
    public String selectMaxCaseIdByYear(String year) {
        return mapper.selectMaxCaseIdByYear(year);
    }

}